import 'package:erp/Entity/Product.dart';
import 'package:erp/Entity/ProductType.dart';
import 'package:erp/Events/EventAddrs.dart';
import 'package:erp/Store/ProductStore.dart';
import 'package:erp/UI/Components/EventfulState.dart';
import 'package:erp/UI/Components/ImageSelector.dart';
import 'package:erp/UI/Components/ListDividerGenerator.dart';
import 'package:erp/UI/Components/LogoScaffold.dart';
import 'package:erp/UI/Components/MessageDialog.dart';
import 'package:erp/UI/Components/ProgressDialog.dart';
import 'package:erp/UI/Components/QuestionDialog.dart';
import 'package:erp/UI/Pages/BasicInformationManagementPages/ProductManagementPages/ProductAddtionalPropertyEditDialog.dart';
import 'package:erp/UI/Pages/BasicInformationManagementPages/ProductTypePages/ProductTypePage.dart';
import 'package:erp/global.dart';
import 'package:flutter/material.dart';
import 'package:barcode_scan/barcode_scan.dart';
import 'package:barcode_flutter/barcode_flutter.dart';
import 'dart:convert';

import 'package:image_picker/image_picker.dart';

class AddProductPage extends StatelessWidget {
  Product product;
  OperationMode mode;
  String heroName;

  AddProductPage(this.product, this.mode, {this.heroName}) : assert(heroName != null);

  @override
  Widget build(BuildContext context) {
    return AddProductPageContentStateful(product.clone(), mode, heroName);
  }
}

class AddProductPageContentStateful extends StatefulWidget {
  Product product;
  OperationMode mode;
  String heroName;

  AddProductPageContentStateful(this.product, this.mode, this.heroName);
  @override
  State<StatefulWidget> createState() => AddProductPageContentState(product, mode, heroName);
}

class AddProductPageContentState extends EventfulState<AddProductPageContentStateful> {
  //region VARIABLES
  AddProductPageContentState(this.product, this.mode, this.heroName);
  bool isAddtionalContentExanded = false;
  SelectResult imageResult;
  OperationMode mode;
  String heroName;
  ProductType defaultType;
  var actionButtons = <Widget>[];

  TextEditingController _barCodeTextController;
  TextEditingController _nameUgTextController;
  TextEditingController _nameZhTextController;
  TextEditingController _productCodeTextController;
  TextEditingController _inPriceTextController;
  TextEditingController _sellPriceTextController;
  TextEditingController _maxCountTextController;
  TextEditingController _minCountTextController;
  TextEditingController _unitTextController;
  TextEditingController _commentTextController;

  ProgressDialog progressDialog;


  Product product;
  InputBorder textFieldBorder = OutlineInputBorder(
      borderSide: BorderSide(
        style: BorderStyle.none,
      )
  );
  Decoration cardDecoration = BoxDecoration(
      color: Color(0xffffffff),
      borderRadius: BorderRadius.circular(15.0),
      border: Border.all(width: 0.1, color: Colors.black26)
  );

  bool get contentEditable => mode == OperationMode.ADD || mode == OperationMode.EDIT;

  //endregion

  void bindEvents(){
    eventIds = [
      bus.subscribe(Events.PRODUCTTYPE_SELECT_SUCCESS, (bus, data){setState(() {});}),
      bus.subscribe<String>(Events.PRODUCTCODE_GENERATE_SUCCESS, (bus, code){setState(() {
        _productCodeTextController.text = code;
        product.code = code;
      });}),
      bus.subscribe(Events.PRODUCTCODE_GENERATE_ERROR, (bus, error){showMessageDialog(context, title: "تاۋار نومۇرى ھاسىللاشتا خاتالىق كۆرۈلدى", content: error.toString());}),
      bus.subscribe<Product>(Events.PRODUCT_DATA_INSERT_SUCCESS, (bus, data){
        progressDialog.close();
        Navigator.of(context).pop();
      }),
      bus.subscribe(Events.PRODUCT_DATA_INSERT_ERROR, (bus, error){
        showMessageDialog(context, title: "قوشۇش مەغلۇپ بولدى", content: error.toString());
        progressDialog.close();
      }),
      bus.subscribe(Events.PRODUCT_DATA_INSERT_REQUEST, (bus, data){
        progressDialog.show();
      }),
      bus.subscribe(Events.PRODUCT_DATA_DELETE_SUCCESS, (bus, product){
        Navigator.of(context).pop();
      }),
      bus.subscribe(Events.PRODUCT_DATA_DELETE_ERROR, (bus, error){
        showMessageDialog(context, title: "ئۆچۈرۈش مەغلۇپ بولدى", content: error.toString());
      }),
      bus.subscribe(Events.PRODUCT_DATA_UPDATE_REQUEST, (bus, data){
        progressDialog.show();
      }),
      bus.subscribe(Events.PRODUCT_DATA_UPDATE_SUCCESS, (bus, data){
        progressDialog.close();
        Navigator.of(context).pop();
      }),
      bus.subscribe(Events.PRODUCT_DATA_UPDATE_ERROR, (bus, error){
        progressDialog.close();
        showMessageDialog(context, title: "يىڭىلاش مەغلۇپ بولدى", content: error.toString());
      }),
    ];
  }

  @override
  void initState() {
    imageResult = SelectResult(
      selected: false,
      imageUrl: product.imgurl,
    );

    bindEvents();

    _barCodeTextController = TextEditingController(text: product.barCode);
    _nameUgTextController = TextEditingController(text: product.nameUg);
//    _nameZhTextController = TextEditingController(text: product.nameZh);
    _productCodeTextController = TextEditingController(text: product.code);
    _inPriceTextController = TextEditingController(text: product.inPrice.toString());
    _sellPriceTextController = TextEditingController(text: product.sellPrice.toString());
    _maxCountTextController = TextEditingController(text: product.maxCount.toString());
    _minCountTextController = TextEditingController(text: product.minCount.toString());
    _unitTextController = TextEditingController(text: product.unit);
    _commentTextController = TextEditingController(text: product.comment);

    ProductType _defaultType = null;
    if (ProductStore.productTypes.length > 0){
      _defaultType = ProductStore.productTypes.first;
    }
    defaultType = ProductStore.productTypes.firstWhere((type) => type.id == product.typeId, orElse: () => _defaultType);

    progressDialog = ProgressDialog(context: context);

    super.initState();

  }

  bool validateContents(){
    product.nameUg = _nameUgTextController.text;
    product.nameZh = _nameUgTextController.text;
    product.inPrice = double.tryParse(_inPriceTextController.text);
    product.sellPrice = double.tryParse(_sellPriceTextController.text);
    product.maxCount = double.tryParse(_maxCountTextController.text);
    product.minCount = double.tryParse(_minCountTextController.text);

    product.unit = _unitTextController.text;
    product.comment = _commentTextController.text;
    product.typeId = defaultType?.id;

    var correct = true;

    correct = (product.nameUg ?? "") != "";
    if (!correct){
      showMessageDialog(context, title: "ئەسكەرتىش", content: "تاۋار ئىسمى قۇرۇق بولسا بولمايدۇ، تاۋار ئىسمىنى تەكشۈرۈپ قايتا سىناپ بىقىڭ");
      return false;
    }
    correct = (product.inPrice ?? 0.0) > 0.0;
    if (!correct){
      showMessageDialog(context, title: "ئەسكەرتىش", content: "ئەكىرىش باھاسىنى كىرگۈزۈش تەلەپ قىلىنىدۇ");
      return false;
    }
    correct = (product.sellPrice ?? 0.0) > 0.0;
    if (!correct){
      showMessageDialog(context, title: "ئەسكەرتىش", content: "سىتىش باھاسىنى كىرگۈزۈش تەلەپ قىلىنىدۇ");
      return false;
    }
    correct = product.inPrice < product.sellPrice;
    if (!correct){
      showMessageDialog(context, title: "ئەسكەرتىش", content: "ئەكىرىش باھاسى سىتىش باھاسىدىن چوڭ كىرگۈزۈشكە يول قويۇلمايدۇ، تەكشۈرگەندىن كىيىن قايتا كىرگۈزۈڭ");
      return false;
    }
    correct = !((product.maxCount ?? 0.0) < 0);
    if (!correct){
      showMessageDialog(context, title: "ئەسكەرتىش", content: "ئەڭ يۇقىرى چىكى توغرا ئەمەس، تەكشۈرگەندىن كىيىن قايتا سىناپ بىقىڭ");
      return false;
    }
    correct = !((product.minCount ?? 0.0) < 0);
    if (!correct){
      showMessageDialog(context, title: "ئەسكەرتىش", content: "ئەڭ تۆۋەن چىكى توغرا ئەمەس، تەكشۈرگەندىن كىيىن قايتا سىناپ بىقىڭ");
      return false;
    }
    correct = (product.unit ?? "") != "";
    if (!correct){
      showMessageDialog(context, title: "ئەسكەرتىش", content: "تاۋار بىرلىكىنى كىرگۈزۈڭ، (مەسىلەن: دانە، كىلوگىرام، پارچە... دىگەندەك)");
      return false;
    }
    correct = (product.code ?? "") != "";
    if (!correct){
      showMessageDialog(context, title: "ئەسكەرتىش", content: "تاۋار نومۇرىنى كىرگۈزۈڭ");
      return false;
    }
    correct = product.typeId != null;
    if (!correct){
      showMessageDialog(context, title: "ئەسكەرتىش", content: "تاۋار تۈرىنى تاللاڭ");
      return false;
    }
    return true;
  }

  Future<void> addProduct() async {
    if (!validateContents()) return;

    product.imgurl = await imageResult.getBase64String();
    bus.publish(Events.PRODUCT_DATA_INSERT_REQUEST, product);
  }

  @override
  Widget build(BuildContext context) {
    actionButtons.clear();

    if (mode == OperationMode.ADD){
      actionButtons.add(FloatingActionButton(
        heroTag: "AddTag",
        child: Icon(Icons.save),
        onPressed: () async {
          await addProduct();
        },
      ));
    }
    if (mode == OperationMode.EDIT){
      actionButtons.add(FloatingActionButton(
        heroTag: "EditTag",
        child: Icon(Icons.save),
        onPressed: () async {
          if (validateContents())
            {
              if (imageResult.selected) product.imgurl = await imageResult.getBase64String();
              bus.publish(Events.PRODUCT_DATA_UPDATE_REQUEST, product);
            }
        },
      ));
    }
    if (mode == OperationMode.DETAIL){
      actionButtons.add(FloatingActionButton(
        backgroundColor: Colors.red,
          heroTag: "DeleteTag",
          child: Icon(Icons.delete_forever),
          onPressed: () async {
            var result = await showQuestionDialog(context, title: "ئۆچۈرۈش ئۈچۈن تۆۋەندىكى تەڭلىمىنى يىشىڭ", content: "y=3sinχ-2cosχ ; χ=π", cancelButtonText: "ئۇھ...", confirmButtonText: "تاپتىم") ?? false;
            if (result) {
              bus.publish(Events.PRODUCT_DATA_DELETE_REQUEST, product);
            }
          }
      ));
      actionButtons.add(FloatingActionButton(
        heroTag: "DetailTag",
        child: Icon(Icons.edit),
        onPressed: (){
          setState(() {
            mode = OperationMode.EDIT;
          });
        },
      ));
    }

    return Hero(tag: heroName, child: LogoScaffold(
      title: "تاۋار ئۇچۇرى",
      assetsLogoName: "assets/pictures/design.png",
      heroName: "hero",
      contentDelegate: SliverChildListDelegate([
        buildContent(context)
      ]),
      floatingActionButton: Row(
        mainAxisAlignment: MainAxisAlignment.center,
        children: ListDividerGenerator(actionButtons, SizedBox(width: 20.0,)).items,
      )
    ));
  }


  Widget buildContent(BuildContext context) {
    return Align(
      child: Container(
        width: 320.0,
//            color: Colors.red,
        child: Column(
          children: <Widget>[
            Padding(
              padding: EdgeInsets.symmetric(vertical: 15.0),
              child: ImageSelector(
                imageResult,
                enabled: contentEditable,
              ),
            ),
            Padding(
              padding: EdgeInsets.symmetric(vertical: 15.0),
              child: Container(
                decoration: cardDecoration,
                child: Column(
                  children: <Widget>[
                    TextField(
                      enabled: contentEditable,
                      decoration: InputDecoration(
                        hintText: "تاۋار ئىسمىنى كىرگۈزۈڭ",
                        labelText: "تاۋار ئىسمى",
                        prefixIcon: Icon(Icons.edit),

                        border: textFieldBorder,
                        enabledBorder: textFieldBorder,
                        focusedBorder: textFieldBorder,
                      ),
                      controller: _nameUgTextController,
                    ),
                    Divider(),
//                    TextField(
//                      decoration: InputDecoration(
//                        hintText: "中文名称",
//                        labelText: "中文名称",
//                        prefixIcon: Icon(Icons.edit),
//
//                        border: textFieldBorder,
//                        enabledBorder: textFieldBorder,
//                        focusedBorder: textFieldBorder,
//                      ),
//                      controller: _nameZhTextController,
//                    ),
//                    Divider(),
                    Row(
                      crossAxisAlignment: CrossAxisAlignment.end,
                      children: <Widget>[
                        Expanded(
                          child: TextField(
                            enabled: contentEditable,
                            decoration: InputDecoration(
                              hintText: "تاۋار نومۇرىنى كىرگۈزۈڭ",
                              labelText: "تاۋار نومۇرى",
                              prefixIcon: Icon(Icons.confirmation_number),

                              border: textFieldBorder,
                              enabledBorder: textFieldBorder,
                              focusedBorder: textFieldBorder,
                            ),
                            controller: _productCodeTextController,
                          ),
                        ),
                        IconButton(
//                      child: Text("ئاپتوماتىك ئېلىش"),
                            icon: Icon(Icons.autorenew),
                            onPressed: !contentEditable ? null : (){
                              bus.publish(Events.PRODUCTCODE_GENERATE_REQUEST, null);
                            }
                        )
                      ],
                    ),
                    Divider(),
                    SizedBox(height: 10.0,),
                    buildBarCode(),
                    SizedBox(height: 10.0,),
                    Row(
                      children: <Widget>[
                        Expanded(
                          child: TextField(
                            enabled: contentEditable,
                            decoration: InputDecoration(
                              hintText: "تاۋار تاياقچە كودىنى كىرگۈزۈڭ",
                              labelText: "تاۋار تاياقچە كودى",
                              prefixIcon: Icon(Icons.local_bar),
                              border: textFieldBorder,
                              enabledBorder: textFieldBorder,
                              focusedBorder: textFieldBorder,
                            ),
                            controller: _barCodeTextController,
                            onChanged: (text){
                              setState(() {
                                product.barCode = text;
                              });
                            },
                          ),
                        ),
                        IconButton(
//                      child: Text("كامېرادىن ئوقۇش"),
                            icon: Icon(Icons.camera_alt),
                            onPressed: !contentEditable ? null : () async {
                              try {
                                var barCode = await BarcodeScanner.scan();
                                if (barCode != null){
                                  setState(() {
                                    product.barCode = barCode;
                                    _barCodeTextController.text = barCode;
                                  });
                                }
                              }
                              on FormatException catch (exception){}
                              catch (exception){
                                showMessageDialog(context, title: "خاتالىق يۈر بەردى", content: exception.toString());
                              }
                            },
                        )
                      ],
                    ),
                    Divider(),
                    TextField(
                      enabled: contentEditable,
                      decoration: InputDecoration(
                        hintText: "تاۋار ئەكىرىش باھاسى",
                        labelText: "ئەكىرىش باھاسى",
                        prefixIcon: Icon(Icons.import_export),

                        border: textFieldBorder,
                        enabledBorder: textFieldBorder,
                        focusedBorder: textFieldBorder,
                      ),
                      keyboardType: TextInputType.numberWithOptions(
                          decimal: true
                      ),
                      controller: _inPriceTextController,
                    ),
                    Divider(),
                    TextField(
                      enabled: contentEditable,
                      decoration: InputDecoration(
                        hintText: "تاۋار سىتىش باھاسى",
                        labelText: "سىتىش باھاسى",
                        prefixIcon: Icon(Icons.import_export),

                        border: textFieldBorder,
                        enabledBorder: textFieldBorder,
                        focusedBorder: textFieldBorder,
                      ),
                      keyboardType: TextInputType.numberWithOptions(
                          decimal: true
                      ),
                      controller: _sellPriceTextController,
                    ),
                    Divider(),
                    TextField(
                      enabled: contentEditable,
                      decoration: InputDecoration(
                        hintText: "ئەڭ يۇقىرى ئەكىرىش چىكى",
                        labelText: "ئەڭ يۇقىرى ئەكىرىش چىكى",
                        prefixIcon: Icon(Icons.account_balance_wallet),

                        border: textFieldBorder,
                        enabledBorder: textFieldBorder,
                        focusedBorder: textFieldBorder,
                      ),
                      keyboardType: TextInputType.numberWithOptions(
                          decimal: false
                      ),
                      controller: _maxCountTextController,
                    ),
                    Divider(),
                    TextField(
                      enabled: contentEditable,
                      decoration: InputDecoration(
                        hintText: "ئەڭ تۆۋەن ئەكىرىش چىكى",
                        labelText: "ئەڭ تۆۋەن ئەكىرىش چىكى",
                        prefixIcon: Icon(Icons.account_balance_wallet),

                        border: textFieldBorder,
                        enabledBorder: textFieldBorder,
                        focusedBorder: textFieldBorder,
                      ),
                      keyboardType: TextInputType.numberWithOptions(
                          decimal: false
                      ),
                      controller: _minCountTextController,
                    ),
                  ],
                ),
              ),
            ),

            Padding(
              padding: EdgeInsets.symmetric(vertical: 15.0),
              child: Container(
                decoration: cardDecoration,
                child: Column(
                  children: <Widget>[
                    TextField(
                      enabled: contentEditable,
                      decoration: InputDecoration(
                        hintText: "تاۋار بىرلىكى",
                        labelText: "تاۋار بىرلىكى",
                        prefixIcon: Icon(Icons.account_balance_wallet),

                        border: textFieldBorder,
                        enabledBorder: textFieldBorder,
                        focusedBorder: textFieldBorder,
                      ),
                      controller: _unitTextController,
                    ),
                    Divider(),
                    Row(
                      children: <Widget>[
                        Padding(
                          padding: EdgeInsets.symmetric(horizontal: 13.0),
                          child: Icon(Icons.format_list_numbered),
                        ),
                        Expanded(
                          flex: 1,
                          child: Text("تاۋار تۈرى:"),
                        ),
                        Expanded(
                            flex: 2,
                            child: RaisedButton(
                              child: Text(defaultType?.name ?? "چىكىپ تاۋار تۈرى تاللاڭ"),
                                onPressed: !contentEditable ? null : () async {
                                  var selectedItem = await Navigator.of(context).push<ProductType>(MaterialPageRoute(builder: (context) => ProductTypePage(true)));
                                  if (selectedItem != null){
                                    defaultType = selectedItem;
                                  }
                                }
                            )
                        )
                      ],
                    ),

                  ],
                ),
              ),
            ),

            Padding(
                padding: EdgeInsets.symmetric(vertical: 15.0),
                child: ExpansionPanelList(
                  expansionCallback: (index, expanded){
                    setState(() {
                      isAddtionalContentExanded = !expanded;
                    });
                  },
                  children: <ExpansionPanel>[
                    ExpansionPanel(
                        isExpanded: isAddtionalContentExanded,
                        headerBuilder: (context, expanded){
                          return Center(
                            child: Text("قوشۇمچە خاسلىقلار"),
                          );
                        },
                        body: Column(
                          children: buildAllAddtionalPropertyItems(context),
                        )
                    )
                  ],
                )
            ),

            Padding(
              padding: EdgeInsets.symmetric(vertical: 15.0),
              child: Container(
                decoration: cardDecoration,
                child: TextField(
                  enabled: contentEditable,
                  decoration: InputDecoration(
                    hintText: "زۆرۈر بولمىسا يازمىسىڭىزمۇ بولىدۇ",
                    labelText: "ئىزاھات",

//                      prefixIcon: Icon(Icons.account_balance_wallet),
                    border: textFieldBorder,
                    enabledBorder: textFieldBorder,
                    focusedBorder: textFieldBorder,
                  ),
                  maxLines: 4,
                  controller: _commentTextController,
                ),
              ),
            ),

            SizedBox(height: 400.0,)
          ],
        ),
      ),
    );
  }

  Widget buildAddtionalPropertyItem(BuildContext context, AddtionalProperty data){
    return ListTile(
      leading: Icon(Icons.format_list_numbered),
      title: Text(data.key ?? ""),
      subtitle: Text(data.value ?? ""),

      trailing: Wrap(
        children: <Widget>[
          IconButton(
              icon: Icon(Icons.edit),
              onPressed: !contentEditable ? null : () async {
                var newData = AddtionalProperty(key: data.key, value: data.value);

                var result = await showProductAddtionalPropertyEditDialog(context, newData);
                if (result){
                  var property = product.addtionalProperties.firstWhere((property) => property.key == data.key);
                  setState(() {
                    property.key = newData.key;
                    property.value = newData.value;
                  });
                }
              }
          ),
          IconButton(
              icon: Icon(Icons.delete),
              onPressed: !contentEditable ? null : (){
                setState(() {
                  product.addtionalProperties.remove(data);
                });
              }
          ),
        ],
      ),

    );
  }

  List<Widget> buildAllAddtionalPropertyItems(BuildContext context){
    var items = product.addtionalProperties.map((property) => buildAddtionalPropertyItem(context, property)).toList();
    items.add(Center(
      child: IconButton(
          icon: Icon(Icons.add),
          onPressed: !contentEditable ? null : () async {
            var data = AddtionalProperty();
            var result = await showProductAddtionalPropertyEditDialog(context, data);
            if (result){
              setState(() {
                product.addtionalProperties.add(data);
              });
            }
          }
      ),
    ));
    return new ListDividerGenerator(items, Divider()).items;
  }

  Widget buildBarCode(){
    Widget widget = SizedBox(height: 5.0,);
    try {
      if (product.barCode != "")
        widget = BarCodeImage(
          data: product.barCode,
          codeType: BarCodeType.CodeEAN13,
          barHeight: 60.0,
          hasText: true,
        );
    }
    catch (exception){

    }

    return widget;
  }
}

enum OperationMode{
  ADD, EDIT, DETAIL
}